<template>
	<view class="container">
		<!-- 状态栏占位 -->
		<view class="status-bar"></view>

		<!-- 页面头部 -->
		<view class="header">
			<view class="back-btn">
				<u-icon name="arrow-left" bold color="#000" size="30rpx" @click="onBack()"></u-icon>
			</view>
			<view class="title">订单详情</view>
			<view class="header-right" @click="showRefundAndChangePolicyPopup = true">
				退改规则
			</view>
		</view>

		<scroll-view class="scroll-content" scroll-y="true">
			<!-- 倒计时提醒 -->
			<view class="countdown-box" v-if="showCountdown">
				<image src="/static/order/PendingPayment.png" mode=""></image>
				<text class="countdown-text">待付款，剩余</text>
				<text class="countdown-time">{{ countdownText }}</text>
			</view>

			<view class="countdown-box" v-if="pageData.orderStatus == 2">
				<image src="/static/order/pedding.png" mode=""></image>
				<text class="countdown-text">订单已付款</text>
			</view>
			<view class="countdown-box" v-if="pageData.orderStatus == 3">
				<image src="/static/order/complete.png" mode=""></image>
				<text class="countdown-text">订单已完成</text>
			</view>
			<view class="countdown-box" v-if="pageData.orderStatus == 4">
				<image src="/static/order/info.png" mode=""></image>
				<text class="countdown-text">订单已取消</text>
			</view>

			<!-- 提示信息 -->
			<view class="tip-box" v-if="showCountdown">
				<text class="tip-icon">⏰</text>
				<text class="tip-text">若买家在30分钟内未付款，订单将自动取消</text>
			</view>

			<!-- 评价信息 -->
			<view class="section"
				v-if="(pageData.orderStatus == 3) && (!pageData.commentType || pageData.commentType == 0)">
				<view class="section-title-evaluate">
					<view>评价本次服务</view>
					<view class="section-title-right-evaluate" v-if="pageData.specialRequirements">
						<view class="">
							（评价成功可获得{{pageData.specialRequirements}}蜂蜜币
						</view>
						<view class="">
							<image src="/static/index/wellet-fm.png" mode=""></image>
						</view>
						<view class="">
							）
						</view>
					</view>
				</view>
				<view class="evaluate">
					<text class="label">
						<u-rate :count="countEvaluate" v-model="evaluate" size="50rpx" active-color="#FA3534"
							inactive-color="#C2C0C0"></u-rate>
					</text>
					<text class="value">{{ evaluate ? evaluateTextMap[evaluate] : '点击进行评价' }}</text>
				</view>
				<u-divider text="" style="margin: 0;"></u-divider>
				<view class="content-box-type2-footer">
					<view class="My-textarea">
						<uni-easyinput type="textarea" v-model="queryParams.remark"
							placeholder="评价本次服务，30字+2张以上图片，即可获得50蜂蜜币奖励~" :inputBorder="false" maxlength="150"
							:styles="{backgroundColor: '#fff',color: '#333',borderColor: '#ddd'}"></uni-easyinput>
						<view class="inputCount">
							{{ queryParams.remark.length || 0 }}/150
						</view>
					</view>

					<!-- 图片上传组件 -->
					<view class="image-upload-section">
						<image-upload ref="imageUploadRef" :maxCount="5" :uploadText="'添加图片'"
							:initialFileList="uploadedImages" @upload-success="onImageUploadSuccess"
							@upload-error="onImageUploadError" @file-deleted="onImageDeleted" />
					</view>
				</view>

				<view class="section-emit" @click="handleEvaluate(evaluate,queryParams.remark,uploadedImages)">
					提交
				</view>
			</view>

			<!-- 已完成评价的展示 -->
			<view class="EvaluationCompleted"
				v-if="(pageData.orderStatus == 3) && (pageData.commentType && pageData.commentType != 0)">
				<view class="EvaluationCompleted-left">
					<image src="/static/order/EvaluationCompleted.png" mode=""></image>
					<span>订单已评价成功！本次获得50蜂蜜值</span>
				</view>

				<view class="">
					<u-icon name="arrow-right" bold color="#fff" size="30rpx"></u-icon>
				</view>
			</view>

			<!-- 订单信息 -->
			<view class=" section">
				<text class="section-title">订单信息</text>
				<view class="info-item">
					<text class="label">服务类型</text>
					<text class="value">{{ pageData.serviceType }}</text>
				</view>
				<view class="info-item">
					<text class="label">订单编号</text>
					<text class="value">{{ pageData.orderNo }} <text class="copy-btn"
							@click="copyOrderNo(pageData.orderNo)">复制</text></text>
				</view>
				<view class="info-item">
					<text class="label">下单时间</text>
					<text class="value">{{ $formatDateTime(pageData.createdAt) }}</text>
				</view>

				<view class="info-item" v-if="pageData.orderStatus != 1">
					<text class="label">付款时间</text>
					<text class="value">{{ $formatDateTime(pageData.serviceDate) }}</text>
				</view>

				<view class="info-item" v-if="pageData.orderStatus != 1">
					<text class="label">付款方式</text>
					<text class="value">{{ pageData.payType }}</text>
				</view>
			</view>

			<!-- 出行信息 -->
			<view class="section">
				<text class="section-title">出行信息</text>
				<view class="info-item">
					<text class="label">向导名称</text>
					<text class="value">{{ pageData.userName }}</text>
				</view>
				<view class="info-item">
					<text class="label">出行日期</text>
					<text class="value">{{ pageData.startTime }} 至 {{ pageData.endTime }}</text>
				</view>
				<view class="info-item">
					<text class="label">出行人数</text>
					<text class="value">{{ pageData.companionsCount }}人</text>
				</view>
			</view>

			<!-- 订单明细 -->
			<view class="section">
				<text class="section-title">订单明细</text>
				<view class="amount-item">
					<text class="amount-label">商品总额</text>
					<text class="amount-value">¥{{ pageData.unitPrice }}</text>
				</view>
				<view class="amount-item">
					<text class="amount-label">蜂蜜币抵扣</text>
					<text class="amount-value">¥ {{ pageData.honeyMoney / 100 }}</text>
				</view>
				<view class="total">
					<text class="amount-label">实付款</text>
					<text class="amount-value-payTotal">¥ {{pageData.totalAmount}}</text>
				</view>
			</view>
		</scroll-view>

		<!-- 底部操作区 -->
		<view class="footer">
			<view class="contact-service">
				<image src="/static/serve.png" class="icon" />
				<view class="text">联系客服</view>
			</view>
			<view class="footer-btn">
				<button class="online-btn-gray" v-if="pageData.orderStatus <= 2"
					@click="showCancelPopup = true">取消订单</button>
				<button class="online-btn" v-if="pageData.orderStatus == 1">立即付款</button>
				<button class="online-btn" v-if="pageData.orderStatus == 3" @click="handleToServer">申请售后</button>
			</view>
		</view>

		<!-- 取消订单弹框组件 -->
		<cancel-order-popup :show="showCancelPopup" :refundAmount="refundAmount" @update:show="showCancelPopup = $event"
			@submit="handleCancelOrder" @close="handlePopupClose" />
		<!-- 取消订单弹框组件 -->
		<RefundAndChangePolicy :show="showRefundAndChangePolicyPopup" :tableData="deductionConfigList"
			@close="handleRefundAndChangePolicyClose" />
	</view>
</template>

<script>
	import {
		getOrderDetail,
		guideComment,
		updateOrdersStatus,
		getDeductionConfigList
	} from '@/request/api.js';
	import CancelOrderPopup from './modal/cancel-order-popup.vue';
	import RefundAndChangePolicy from './modal/RefundAndChangePolicy.vue';
	import ImageUpload from '@/components/ImageUpload/ImageUpload.vue';

	export default {
		components: {
			CancelOrderPopup,
			ImageUpload,
			RefundAndChangePolicy
		},
		data() {
			return {
				pageData: {},
				countdownInterval: null,
				remainingTime: 0, // 剩余时间（秒）
				countEvaluate: 5,
				evaluate: 0,
				evaluateTextMap: {
					1: '差',
					2: '不太满意',
					3: '一般',
					4: '很不错',
					5: '太棒了'
				},
				showCancelPopup: false, // 取消订单弹框显示状态
				refundAmount: 300, // 示例金额，实际从 pageData 获取
				queryParams: {
					remark: ''
				},
				// 图片上传相关
				uploadedImages: [], // 已上传的图片列表

				// 提交按钮控制
				isSubmitting: false, // 防止重复提交标志
				submitTimeout: null, // 防抖定时器

				// 退改规则
				showRefundAndChangePolicyPopup: false,
				deductionConfigList: []
			}
		},
		computed: {
			// 是否显示倒计时区域
			showCountdown() {
				// 只有待付款状态且倒计时尚未结束才显示
				return this.pageData.orderStatus == '1' && this.remainingTime > 0;
			},
			// 格式化倒计时显示文本
			countdownText() {
				const minutes = Math.floor(this.remainingTime / 60);
				const seconds = this.remainingTime % 60;
				return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
			}
		},
		onLoad(option) {
			if (option.id) {
				this.getDetail(option.id)
				this.getConfigList()
			}
		},
		beforeDestroy() {
			// 组件销毁前清除定时器
			if (this.countdownInterval) {
				clearInterval(this.countdownInterval);
			}
		},
		methods: {
			// 退改规则
			getConfigList() {
				getDeductionConfigList().then(res => {
					if (res.data.code == 200) {
						this.deductionConfigList = res.data.rows
					}
				})
			},
			// 申请售后
			handleToServer() {
				uni.navigateTo({
					url: '/pages_sub/order/after-sales-service'
				})
			},
			getDetail(id) {
				getOrderDetail(id).then(res => {
					if (res.data.code == 200) {
						this.pageData = res.data.data
						this.initCountdown();
						if (this.pageData.commentType && this.pageData.commentType != 0) {
							this.evaluate = this.pageData.commentType
							this.queryParams.remark = this.pageData.content
						}
						// 处理图片回显
						this.handleImageEcho();
					}
				})
			},
			// 专门处理图片回显的方法
			handleImageEcho() {
				this.uploadedImages = [];

				if (!this.pageData.files || !Array.isArray(this.pageData.files)) {
					return;
				}

				try {
					console.log('原始files数据:', this.pageData.files);

					// 过滤出有 fileUrl 的对象，并转换为组件需要的格式
					this.uploadedImages = this.pageData.files
						.filter(file => file && file.fileUrl && typeof file.fileUrl === 'string')
						.map(file => ({
							url: file.fileUrl,
							status: 'success',
							message: ''
						}));

					console.log('处理后的图片列表:', this.uploadedImages);

				} catch (error) {
					console.error('处理图片回显时出错:', error);
					this.uploadedImages = [];
				}
			},
			handleEvaluate(start, mark, imgList) {
				// 防抖处理：如果正在提交中，直接返回
				if (this.isSubmitting) {
					return;
				}

				// 节流处理：清除之前的定时器
				if (this.submitTimeout) {
					clearTimeout(this.submitTimeout);
				}

				// 设置防抖延迟（300毫秒）
				this.submitTimeout = setTimeout(() => {
					this.submitEvaluate(start, mark, imgList);
				}, 300);
			},
			submitEvaluate(start, mark, imgList) {
				// 校验是否选择了星级评价
				if (!start || start === 0) {
					uni.showToast({
						title: '请选择星级评价',
						icon: 'none',
						duration: 2000
					});
					return;
				}

				// 设置提交状态，防止重复提交
				this.isSubmitting = true;

				let arr = imgList.map(item => {
					return {
						fileUrl: item.url,
						isImage: 1
					};
				});

				let params = {
					commentType: start,
					contentType: imgList.length > 0 ? 2 : 1,
					content: mark,
					clientGuideCommentFileList: arr,
					orderId: this.pageData.id,
					guideId: this.pageData.serviceProviderId,
					userId: this.pageData.customerId,
				}

				guideComment(params).then(res => {
					if (res.data.code == 200) {
						uni.showToast({
							title: '评价成功',
							icon: 'none',
							duration: 2000
						});
						setTimeout(() => {
							this.getDetail(this.pageData.id)
						}, 2000)
					}
				}).catch(error => {
					console.error('评价失败:', error);
					uni.showToast({
						title: '评价失败，请重试',
						icon: 'none'
					});
				}).finally(() => {
					// 无论成功失败，都重置提交状态
					this.isSubmitting = false;
				});
			},
			goBack() {
				uni.navigateBack();
			},
			copyOrderNo(order) {
				uni.setClipboardData({
					data: order,
					success: () => {
						uni.showToast({
							title: '复制成功'
						});
					}
				});
			},
			onBack() {
				uni.navigateBack()
			},
			// 初始化倒计时
			initCountdown() {
				// 清除已存在的定时器
				if (this.countdownInterval) {
					clearInterval(this.countdownInterval);
				}

				// 只有待付款状态才需要倒计时
				if (this.pageData.orderStatus != '1') {
					return;
				}

				// 计算剩余时间（假设订单创建时间是 createdAt 字段，格式为时间戳或可解析的时间字符串）
				const orderCreateTime = new Date(this.pageData.createdAt).getTime();
				// 30分钟 = 1800秒
				const expireTime = orderCreateTime + 30 * 60 * 1000;
				const now = new Date().getTime();
				this.remainingTime = Math.floor((expireTime - now) / 1000);

				// 如果已经超时，则不启动倒计时
				if (this.remainingTime <= 0) {
					return;
				}

				// 启动倒计时
				this.countdownInterval = setInterval(() => {
					this.remainingTime--;
					// 倒计时结束，清除定时器
					if (this.remainingTime <= 0) {
						clearInterval(this.countdownInterval);
						// 可以在这里触发订单状态更新等操作
					}
				}, 1000);
			},

			// 处理取消订单提交
			handleCancelOrder(cancelData) {
				// 发起取消订单请求
				uni.showLoading({
					title: '正在取消...'
				});

				let params = {
					orderNo: this.pageData.orderNo,
					remarks: cancelData.reason,
				}
				updateOrdersStatus(params).then((res) => {
					console.log(res);
					if (res.data.code == 200) {
						uni.hideLoading();
						this.showCancelPopup = false;
						uni.showToast({
							title: '取消成功',
							icon: 'none',
							duration: 2000
						});
						setTimeout(() => {
							this.getDetail(this.pageData.id)
						}, 2000);
					}
				}).catch(() => {
					uni.hideLoading();
				});
			},


			// 处理弹框关闭
			handlePopupClose() {
				this.showCancelPopup = false;
			},
			// 处理弹框关闭
			handleRefundAndChangePolicyClose() {
				this.showRefundAndChangePolicyPopup = false;
			},

			// ==================== 图片上传相关方法 ====================
			// 图片上传成功回调
			onImageUploadSuccess(file) {
				console.log('图片上传成功:', file);
				// 更新已上传图片列表
				this.uploadedImages = this.$refs.imageUploadRef.getSuccessFiles().files;
				this.$emit('image-upload-success', file);
			},

			// 图片上传失败回调
			onImageUploadError(error) {
				console.error('图片上传失败:', error);
				uni.showToast({
					title: '图片上传失败',
					icon: 'none'
				});
				this.$emit('image-upload-error', error);
			},

			// 图片删除回调
			onImageDeleted(file) {
				console.log('图片已删除:', file);
				// 更新已上传图片列表
				this.uploadedImages = this.$refs.imageUploadRef.getSuccessFiles().files;
				this.$emit('image-deleted', file);
			},


		}
	}
</script>

<style lang="scss" scoped>
	page {
		background: linear-gradient(to bottom, #FFF1D0, #F8F8F8);
		height: 100vh;
		overflow: hidden;
	}

	.container {
		height: 100vh;
		display: flex;
		flex-direction: column;

		.status-bar {
			height: var(--status-bar-height);
			width: 100%;
			flex-shrink: 0;
		}

		.header {
			display: flex;
			align-items: center;
			justify-content: space-between;
			/* 左右分布 */
			height: 80rpx;
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
			position: relative;
			z-index: 10;
			padding: 0 30rpx;
			box-sizing: border-box;
			margin-top: var(--status-bar-height);

			.back-btn {
				/* 移除绝对定位，使用 flex 布局 */
				display: flex;
				align-items: center;
				justify-content: flex-start;
				width: 80rpx;
				/* 固定宽度保持平衡 */
			}

			.title {
				position: absolute;
				left: 50%;
				transform: translateX(-50%);
				text-align: center;
			}

			.header-right {
				display: flex;
				align-items: center;
				justify-content: flex-end;
				width: 120rpx;
				/* 与左边保持相同宽度 */
				color: #000000;
				/* 可选：给退改规则添加主题色 */
				font-size: 26rpx;
			}
		}

		.scroll-content {
			position: absolute;
			top: calc(80rpx + var(--status-bar-height));
			left: 0;
			right: 0;
			bottom: 160rpx;
			overflow-y: auto;
			box-sizing: border-box;
			background: linear-gradient(to bottom, #FFF1D0, #F8F8F8);

			.countdown-box {
				padding: 20rpx 30rpx;
				display: flex;
				align-items: center;
				font-size: 36rpx;
				color: #333;
				font-weight: bold;

				image {
					margin-right: 20rpx;
					width: 32rpx;
					height: 32rpx;
				}

				.countdown-text {
					color: #000000;
				}

				.countdown-time {
					color: #FF452D;
					margin-left: 10rpx;
				}
			}

			.tip-box {
				margin: 0 30rpx;
				padding: 20rpx 30rpx;
				background-color: #fff;
				display: flex;
				align-items: center;
				font-size: 26rpx;
				color: #666;
				border-radius: 20rpx;

				.tip-icon {
					margin-right: 10rpx;
				}
			}

			.section {
				background-color: #fff;
				padding: 30rpx;
				margin: 20rpx 30rpx 0;
				border-bottom: 1px solid #eee;
				border-radius: 20rpx;

				.section-title {
					font-size: 30rpx;
					font-weight: bold;
					color: #000;
					display: flex;
					align-items: center;

					.section-title-right {
						color: #FE7131;
						font-weight: 400;
						height: 40rpx;
						line-height: 40rpx;

						image {
							width: 40rpx;
							height: 40rpx;
						}
					}
				}

				.section-title-evaluate {
					font-size: 30rpx;
					font-weight: bold;
					color: #000;
					display: flex;
					align-items: center;

					.section-title-right-evaluate {
						color: #FE7131;
						font-weight: 400;
						height: 40rpx;
						line-height: 40rpx;
						display: flex;

						image {
							width: 40rpx;
							height: 40rpx;
						}
					}
				}

				.info-item {
					display: flex;
					justify-content: space-between;
					font-size: 26rpx;
					color: #4D4D56;
					line-height: 90rpx;
					border-bottom: 1rpx solid #2929300D;

					.label {
						color: #999;
					}

					.value {
						color: #000000;
					}

					.copy-btn {
						color: #FE7131;
						margin-left: 10rpx;
					}

					/* 最后一个 item 移除下边框 */
					&:last-child {
						border-bottom: none;
					}
				}

				.evaluate {
					display: flex;
					justify-content: space-between;
					font-size: 26rpx;
					color: #4D4D56;
					line-height: 90rpx;
					align-items: center;
				}

				.content-box-type2-footer {
					margin-top: 20rpx;
					padding-bottom: 20rpx;

					.content-box-type2-footer-bottom {
						font-size: 24rpx;
						color: rgba(120, 120, 130, 1);
						line-height: 26rpx;
						padding-top: 20rpx;
						padding-bottom: 30rpx;
					}

					.My-textarea {
						border-radius: 10rpx;
						position: relative;

						.inputCount {
							position: absolute;
							bottom: 20rpx;
							right: 20rpx;
							font-size: 24rpx;
							color: #999;
							padding: 4rpx 10rpx;
							border-radius: 6rpx;
							background: rgba(255, 255, 255, 0.8);
						}
					}

					// 图片上传区域样式
					.image-upload-section {
						margin-top: 20rpx;

						.upload-title {
							font-size: 28rpx;
							font-weight: bold;
							color: #333;
							display: block;
							margin-bottom: 20rpx;
						}

						.upload-tips {
							font-size: 24rpx;
							color: #FE7131;
							display: block;
							margin-top: 15rpx;
							text-align: center;
						}

					}

					.my-block {
						background: #FFFFFF;
						border-radius: 20rpx;
						overflow: hidden;
						position: relative;

						.tag-header-container {
							display: flex;
							flex-direction: column;

							.selected-tags-container {
								.selected-tags-title {
									font-size: 28rpx;
									font-weight: bold;
									margin-bottom: 20rpx;
									color: #333;
								}

								.selected-tags-list {
									display: flex;
									flex-wrap: wrap;

									.selected-tag-item {
										margin-right: 20rpx;
										margin-bottom: 20rpx;
									}
								}

								.no-tags-prompt {
									color: #999;
									font-size: 28rpx;
									text-align: center;
									padding: 40rpx 0;
								}
							}
						}
					}
				}

				.section-emit {
					background-color: #FE7131;
					color: #fff;
					font-size: 30rpx;
					font-weight: bold;
					border-radius: 30rpx;
					height: 60rpx;
					line-height: 60rpx;
					text-align: center;
				}
			}

			.EvaluationCompleted {
				display: flex;
				justify-content: space-between;
				align-items: center;
				background: linear-gradient(to right, #FE7131, #FFB327);
				margin: 0 30rpx;
				padding: 0 10rpx;
				border-radius: 20rpx;
				box-sizing: border-box;
				height: 80rpx;

				.EvaluationCompleted-left {
					display: flex;
					align-items: center;
					color: #fff;
					font-size: 26rpx;
					font-weight: bold;

					image {
						width: 100rpx;
						height: 100rpx;
					}
				}
			}

			.amount-item {
				display: flex;
				justify-content: space-between;
				font-size: 28rpx;
				line-height: 90rpx;
				border-bottom: 1rpx solid #2929300D;

				.amount-label {
					color: #666;
				}

				.amount-value {
					color: #333;
				}

				.amount-value-payTotal {
					color: #FE7131;
				}
			}

			.total {
				display: flex;
				justify-content: flex-end;
				font-size: 30rpx;
				line-height: 90rpx;

				.amount-label {
					color: #000000;
					margin-right: 30rpx;
				}

				.amount-value-payTotal {
					color: #FE7131;
				}
			}
		}

		.footer {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			background-color: #fff;
			padding: 30rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
			z-index: 10;

			.contact-service {
				text-align: center;
				color: #666;
				font-size: 28rpx;

				.icon {
					width: 40rpx;
					height: 40rpx;
					margin-right: 10rpx;
				}
			}

			.footer-btn {
				display: flex;

				.online-btn {
					width: 200rpx;
					height: 60rpx;
					background-color: #ff7a00;
					color: white;
					font-size: 28rpx;
					border-radius: 30rpx;
					line-height: 60rpx;
					text-align: center;
				}

				.online-btn-gray {
					width: 200rpx;
					height: 60rpx;
					background-color: #F0EFEF;
					font-size: 28rpx;
					border-radius: 30rpx;
					line-height: 60rpx;
					text-align: center;
				}

				button {
					margin-left: 10rpx;
				}
			}
		}
	}
</style>